﻿@{
    ViewBag.PageTitle = Resources.Intercamber.EstablishmentAdmin_PageName;
}
@section PageHead
{
    <style>
        .tipWidth
        {
            max-width: 500px !important;
        }
    </style>

    <script type="text/javascript">
        var texts = {
            Mandatory: '@Resources.Intercamber.Error_Mandatory',
            Add: '@Resources.Intercamber.Add',
            Update: '@Resources.Intercamber.Update'
        };
        var listProfils = @(Html.Raw(Json.Encode(ViewBag.AllProfils)));
        var listEstablishments = @(Html.Raw(Json.Encode(ViewBag.AllEstablishments)));

        var usersManager = new function() {

            var ttAdd = null;
            this.isCreatingNew = false;
            var editedId = null;
            this.openPopup = function(isNew) {
                usersManager.isCreatingNew = isNew;
                if (ttAdd == null) {
                    ttAdd = $('<div />');
                    ttAdd.qtip({
                        show: {
                            effect: false,
                            modal: { on: true, blur: false }
                        },
                        content: $('#ttAdd'),
                        position: { my: 'center', at: 'center', target: $(window), viewport: $(window), adjust: { method: "shift", x: 0, y: 0 }, effect: false },
                        events: {
                            show: function() {
                                $(this).draggable();
                                $(this).qtip('option', { 'content.title': usersManager.isCreatingNew ? texts.AddEstablishment : texts.UpdateEstablishment, 'content.title.button': 'true' });
                            },
                            hide: function() {
                                $(this).qtip('option', { 'position.my': 'top left', 'position.target': [$(this).offset().left, $(this).offset().top] });
                            }
                        },
                        hide: false,
                        style: { classes: "qtip-bootstrap qtip-rounded tipWidth", tip: false }
                    });
                }
                ttAdd.qtip('option', 'content.title', isNew ? texts.Add : texts.Update);
                // reset form 
                if (usersManager.isCreatingNew) {
                    $("#LblFirstName").val("");
                    $("#LblLastName").val("");
                    $("#LblEmail").val("");
                    $("#LblPassword").val("");
                    $("#CbEnabled").prop("checked", true);
                } else {
                    var data = null;
                    var allTabData = $("#gridUsers").getGridParam('userData');
                    for (var i = 0, max = allTabData.length; i < max; i++)
                        if (allTabData[i].IdUser == editedId) {
                            data = allTabData[i];
                            break;
                        }
                    $("#LblFirstName").val(data.FirstName);
                    $("#LblLastName").val(data.LastName);
                    $("#LblEmail").val(data.Email);
                    $("#LblPassword").val("");
                    $("#DdlProfil").val(data.IdProfil);
                    $("#DdlEstablishment").val(data.IdEstablishment);
                    $("#CbEnabled").prop("checked", data.Active);
                }

                ttAdd.qtip('show');
            };

            this.popupHide = function() {
                ttAdd.qtip('hide');
            };

            this.save = function() {
                var valFirstName = $("#LblFirstName").val();
                var valLastName = $("#LblLastName").val();
                var valEmail = $("#LblEmail").val();
                var valPassword = $("#LblPassword").val();
                if (valPassword.length > 0)
                    valPassword = Sha256(valPassword);
                var valProfil = $("#DdlProfil").val();
                var valEstablishment = $("#DdlEstablishment").val();
                var valEnabled = $("#CbEnabled").prop("checked");

                // checks
                if (valEmail == "") {
                    alert(texts.Mandatory.replace("{0}", "@Resources.Intercamber.Email"));
                    return;
                }
                if (valFirstName == "") {
                    alert(texts.Mandatory.replace("{0}", "@Resources.Intercamber.FirstName"));
                    return;
                }
                if (valLastName == "") {
                    alert(texts.Mandatory.replace("{0}", "@Resources.Intercamber.LastName"));
                    return;
                }
                if (valPassword == "" && usersManager.isCreatingNew) {
                    alert(texts.Mandatory.replace("{0}", "@Resources.Intercamber.Password"));
                    return;
                }

                this.popupHide();
                $("#loading").show();

                var saveUrl = usersManager.isCreatingNew ? "/Admin/AddUser" : "/Admin/UpdateUser";
                var jsonParams = "{" + (usersManager.isCreatingNew ? "" : "'u.IdUser':'" + editedId + "', ") +
                    "'u.FirstName':\"" + valFirstName.replace("\"", "") + "\", 'u.LastName':\"" + valLastName.replace("\"", "") + "\", 'u.Email': \"" + valEmail.replace("\"", "") + "\", " +
                    "'u.Password':\"" + valPassword + "\", 'u.IdProfil':" + valProfil + ", 'u.IdEstablishment':" + valEstablishment + ", 'u.Active':" + (valEnabled ? "true" : "false")+ "}";

                $.ajax({
                    type: "POST",
                    url: saveUrl,
                    contentType: "application/json; charset=utf-8",
                    data: jsonParams,
                    dataType: "json",
                    success: function(result) {
                        $("#loading").hide();
                        if (result == null)
                            usersManager.reloadGrid();
                        else
                            alert(result);
                    },
                    error: function(result) { debugger; }
                });
                
                ttAdd.qtip('hide');
            };

            this.init = function() {
                $("#gridUsers").jqGrid({
                    autowidth: true,
                    datatype: 'json',
                    width: '100%',
                    height: '100%',
                    jsonReader: { 'repeatitems': false, 'id': 'IdUser', userdata : 'rows', root: 'rows' },
                    loadonce: false,
                    pager: '#gridUsers_pager',
                    rowList: [10, 25, 50],
                    rowNum: 10,
                    url: '/Admin/UsersData',
                    viewrecords: true,
                    colModel: [
                        { name: 'IdUser', fixed: true, formatter: usersManager.gridColumnEdit, label: '@Resources.Intercamber.Edit', resizable: false, sortable: false, width: 45, index: 'IdEstablishment', align: 'center' },
                        { name: 'Profil', label: '@Resources.Intercamber.Profil', align: 'center', width: 30, formatter: usersManager.viewProfileFormater },
                        { name: 'FirstName', formatter: usersManager.gridColumnName, label: '@Resources.Intercamber.Name', align: 'center' },
                        { name: 'IdProfil', formatter: usersManager.gridColumnProfil, label: '@Resources.Intercamber.Profil', align: 'center', width: 100 },
                        { name: 'IdEstablishment', formatter: usersManager.gridColumnEstablishment, label: '@Resources.Intercamber.Establishment', align: 'center', width: 220 },
                        { name: 'Active', formatter: usersManager.gridColumnActive, label: '@Resources.Intercamber.Enabled', align: 'center', width: 70 },
                    ],
                    subGrid: false,
                    loadComplete: function() {
                        $("#gridUsers").jqGrid('setGridWidth', 800, true);
                    },
                });
                usersManager.reloadGrid();

                var i;
                var ddlProfils = $("#filterProfils");
                var editorProfils = $("#DdlProfil");
                for (i = 0; i < listProfils.length; i++) {
                    $("<option value='" + listProfils[i].Id + "'>" + listProfils[i].Label + "</option>").appendTo(ddlProfils);
                    $("<option value='" + listProfils[i].Id + "'>" + listProfils[i].Label + "</option>").appendTo(editorProfils);
                }
                if (listEstablishments != null) {
                    var ddlEst = $("#filterEstablishment");
                    var editorEst = $("#DdlEstablishment");
                    for (i = 0; i < listEstablishments.length; i++) {
                        $("<option value='" + listEstablishments[i].Id + "'>" + listEstablishments[i].Label + "</option>").appendTo(ddlEst);
                        $("<option value='" + listEstablishments[i].Id + "'>" + listEstablishments[i].Label + "</option>").appendTo(editorEst);
                    }
                }
            };

            this.reloadGrid = function() {
                var url = "/Admin/UsersData?idProfil=" + $("#filterProfils").val() + "&name=" + $("#filterName").val() + "&idEstablishment=" + $("#filterEstablishment").val();
                $("#gridUsers").jqGrid().setGridParam({
                    datatype: 'json',
                    url: url
                }).trigger("reloadGrid", [{ page: 1 }]);
            };

            this.gridColumnEdit = function(cellvalue) {
                return "<img id=\"add" + cellvalue + "\" title=\"\" class='imgButton' src='/Images/Edit.gif' onclick=\"usersManager.edit(" + cellvalue + ");\" />";
            };
            this.gridColumnName = function(cellvalue, options, rowobject) {
                return rowobject.FirstName + " " + rowobject.LastName + "<br/><a href='mailto:" + rowobject.Email + "' target='_blank'>" + rowobject.Email + "</a>";
            };
            this.gridColumnProfil = function(cellvalue) {
                for (var i = 0; i < listProfils.length; i++)
                    if (listProfils[i].Id == cellvalue)
                        return listProfils[i].Label;
                return cellvalue;
            };
            this.gridColumnEstablishment = function(cellvalue) {
                for (var i = 0; i < listEstablishments.length; i++)
                    if (listEstablishments[i].Id == cellvalue)
                        return listEstablishments[i].Label;
                return cellvalue;
            };
            this.gridColumnActive = function(cellvalue) {
                return "<img src='../Images/" + (cellvalue ? "Check.png" : "Delete.png") + "' />";
            };
            this.viewProfileFormater = function (cellvalue, options, rowobject) {
                var idUser = rowobject.IdUser;
                if (idUser == null || idUser == 0) return "";
                return "<img onclick='profilViewerManager.showProfil(" + idUser + ");' class='imgButton' src='/Images/Avatar.png' />";
            };

            this.edit = function(id) {
                editedId = id;
                usersManager.openPopup(false);
            };
        };


        $(function() {
            $(".jqbutton").button();
            usersManager.init();
        });

    </script>
    @Html.Partial("~/Views/Shared/_ProfilViewerPartial.cshtml")
}

@section PageLeftBar {
    @Html.Partial("~/Views/Shared/_LeftBarUserDetailPartial.cshtml")
}

@section PageContent {
    <div class="innerTitle ui-corner-all">
        @Resources.Intercamber.UserAdmin_PageName
    </div>
    <br />
    <br />
    <table cellpadding="4">
        <tr>
            <td style="padding-right: 40px;">
                @if (ViewBag.ButtonAddVisible)
                {
                    <button id="btnAdd" class="jqbutton" onclick=" usersManager.openPopup(true); return false; ">@Resources.Intercamber.Add</button>
                }
            </td>
            <td>
                @Resources.Intercamber.Name
                <input type="text" style="width: 180px" id="filterName" />
            </td>
            <td>
                @Resources.Intercamber.Profil
                <select id="filterProfils">
                    <option value="">-- @Resources.Intercamber.All --</option>
                </select>
            </td>
            <td>
                @Resources.Intercamber.Establishment
                <select id="filterEstablishment">
                    <option value="">-- @Resources.Intercamber.All --</option>
                </select>
            </td>
            <td>
                <button class="jqbutton" onclick="usersManager.reloadGrid(); return false;">@Resources.Intercamber.Filter</button>
            </td>
        </tr>
    </table>
    <span id="loading" style="display: none;">
        <img src="~/Images/Loading.gif" />
        @Resources.Intercamber.Loading
    </span>
    <br />
    <table id="gridUsers" style="width: 100%"></table>
    <div id="gridUsers_pager"></div>

    <div id="ttAdd" style="display: none;">
        <table cellpadding="2" cellspacing="2" width="100%">
            <tr>
                <td>
                    @Resources.Intercamber.FirstName
                </td>
                <td width="100%">
                    <input type="text" id="LblFirstName" class="ui-widget-content" style="width: 100%" />
                </td>
            </tr>
            <tr>
                <td>
                    @Resources.Intercamber.LastName
                </td>
                <td>
                    <input type="text" id="LblLastName" class="ui-widget-content" style="width: 100%" />
                </td>
            </tr>
            <tr>
                <td>
                    @Resources.Intercamber.Email
                </td>
                <td>
                    <input type="text" id="LblEmail" class="ui-widget-content" style="width: 100%" />
                </td>
            </tr>
            <tr>
                <td>
                    @Resources.Intercamber.Password
                </td>
                <td>
                    <input type="password" id="LblPassword" class="ui-widget-content" style="width: 100%" />
                </td>
            </tr>
            <tr>
                <td>
                    @Resources.Intercamber.Profil
                </td>
                <td>
                    <select id="DdlProfil">
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    @Resources.Intercamber.Establishment
                </td>
                <td>
                    <select id="DdlEstablishment">
                    </select>
                </td>
            </tr>
            <tr>
                <td>
                    @Resources.Intercamber.Enabled
                </td>
                <td>
                    <input type="checkbox" id="CbEnabled"/>
                </td>
            </tr>
        </table>
        <br />
        <div class="ttButtons">
            <button class="jqbutton" onclick="usersManager.save(); return false; ">@Resources.Intercamber.Ok</button>
            &nbsp;
            <button class="jqbutton" onclick="usersManager.popupHide(); return false;">@Resources.Intercamber.Cancel</button>
        </div>
    </div>

}
